//
//  SEGFaceRecognitionViewModel.m
//  SEGViewModel
//
//  Created by 乔杨 on 2020/7/6.
//

#import "SEGFaceRecognitionViewModel.h"
#import "SEGFaceRecognitionManager.h"

@interface SEGFaceRecognitionViewModel ()

/// 人脸识别请求类
@property (nonatomic, strong) SEGFaceRecognitionManager *reqManager;

@end

@implementation SEGFaceRecognitionViewModel

- (instancetype)init {
    self = [super init];
    if (self) {
        [self seg_createUploadIconCommand];
        [self seg_createDownloadSignal];
    }
    return self;
}
// 上传人脸识别图片
- (void)seg_createUploadIconCommand {
    @weakify(self);
    self.uploadIconCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(UIImage *editedImage) {
        @strongify(self);        
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            [[SEGOnefileuploadManager sharedManager] requestImageUploadToCheckFaceDetection:editedImage serviceType:@"1" completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
                if (!isSuccessed) {
                    [subscriber sendError:error];
                    return;
                }
                NSString *imagePath = result[@"data"];
                
                // 上传人脸识别图片地址
                [self.reqManager seg_saveFacePath:imagePath finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                    if (!isSuccessed) {
                        NSError *error = [NSError errorWithDomain:@"" code:codeType.integerValue userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                        [subscriber sendError:error];
                        return;
                    }
                    
                    RACTuple *tuple = RACTuplePack(imagePath, errorMessage);
                    [subscriber sendNext:tuple];
                    [subscriber sendCompleted];
                }];
            }];
            return nil;
        }];
    }];
}
// 查询人脸识别图片
- (void)seg_createDownloadSignal {
    @weakify(self);
    self.downloadSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        [self.reqManager seg_queryFacePathWithFinished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
           if (!isSuccessed) {
                NSError *error = [NSError errorWithDomain:@"" code:codeType.integerValue userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                [subscriber sendError:error];
                return;
            }
            
            [subscriber sendNext:self.reqManager.facePath];
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
}

#pragma mark - Getter
- (SEGFaceRecognitionManager *)reqManager {
    if (!_reqManager) _reqManager = [SEGFaceRecognitionManager new];
    return _reqManager;
}

@end
